package com.lzxuni.modules.ueditor;

import com.alibaba.fastjson.JSONObject;
import com.lzxuni.common.constant.Constants;
import com.lzxuni.common.utils.FileUtil;
import com.lzxuni.common.utils.MethodUtil;
import com.lzxuni.common.utils.UuidUtil;
import com.lzxuni.config.AttachmentConfig;
import com.lzxuni.modules.common.controller.BaseController;
import com.lzxuni.modules.common.entity.FileEntity;
import com.lzxuni.modules.ueditor.define.AppInfo;
import com.lzxuni.modules.ueditor.define.BaseState;
import com.lzxuni.modules.ueditor.define.MultiState;
import com.lzxuni.modules.ueditor.define.State;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;

/**
 * @author 孙志强
 * @Description: 上传文件controller，图片路径为项目根目录下upload/时间/文件名
 * @date 2017年3月4日 下午1:09:22
 */
@Controller
@RequestMapping("/admin/ueditor")
public class UeditorController extends BaseController {
    @Autowired
    private AttachmentConfig attachmentConfig;
    protected Logger log = LoggerFactory.getLogger(UeditorController.class);

    @RequestMapping(value = "uploadUeditor.html")
    public void uploadUeditor(MultipartFile upfile, String type,
                              HttpServletRequest request, HttpServletResponse response) {
        String date = new SimpleDateFormat("yyyy/MM/dd").format(new Date());
        JSONObject result = new JSONObject();
        try {
            if (upfile != null) {
                // 文件会上传到项目\\upload\\时间\\文件夹中

                String filename = FilenameUtils.getName(upfile.getOriginalFilename());
                String ext = FilenameUtils.getExtension(filename);

                String basePath = attachmentConfig.getPath();

                String realPath = Constants.STATIC_RESOURCE_BASE_PATH + File.separator + date + File.separator;
                String fileName = UuidUtil.get32UUID() + "." + FileUtil.getFileExt(upfile.getOriginalFilename());
                FileUtils.copyInputStreamToFile(upfile.getInputStream(), new File(basePath + realPath, fileName));


                FileEntity fileBean = new FileEntity();
                fileBean.setFileName(fileName);
                fileBean.setRealName(upfile.getOriginalFilename());
                fileBean.setRealSize(upfile.getSize());

                fileBean.setYwType("ueditor");

                fileBean.setRealPath(realPath + fileName);
                fileBean.setSfileName("s" + fileName);
                fileBean.setUrlPath(Constants.STATIC_RESOURCE_BASE_PATH + "/" + date + "/" + fileName);
                System.out.println(fileBean);
                // 需要给页面参数(参考ueditor的/jsp/imageUp.jsp)
                result.put("url", "/" + Constants.STATIC_RESOURCE_BASE_PATH + "/" + date + "/" + fileName);
                result.put("original", upfile.getOriginalFilename());
                result.put("type", ext);
                result.put("state", "SUCCESS");
                result.put("title", "ceshi");
            }
        } catch (Exception e) {
            log.error(e.getClass().getName() + ":" + e.getMessage());
            e.printStackTrace();
            result.put("state", "SUCCESS");
        }
        MethodUtil.writer(response, result.toString());
    }

    @RequestMapping(value = "/imageManager.html")
    public void imageManager(Integer picNum, Boolean insite, HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        State state = listFileByOnline(request, getStartIndex(request));
        MethodUtil.writer(response, state.toJSONString());
    }

    public int getStartIndex(HttpServletRequest request) {
        String start = request.getParameter("start");
        try {
            return Integer.parseInt(start);
        } catch (Exception e) {
            log.error(e.getClass().getName() + ":" + e.getMessage());
            return 0;
        }
    }

    public State listFileByOnline(HttpServletRequest request, int index) {
        String uploadPath = attachmentConfig.getPath() + Constants.STATIC_RESOURCE_BASE_PATH;
        File dir = new File(uploadPath);
        State state = null;
        if (!dir.exists()) {
            return new BaseState(false, AppInfo.NOT_EXIST);
        }
        if (!dir.isDirectory()) {
            return new BaseState(false, AppInfo.NOT_DIRECTORY);
        }
        Collection<File> list = FileUtils.listFiles(dir, null, true);
        if (index < 0 || index > list.size()) {
            state = new MultiState(true);
        } else {
            Object[] fileList = Arrays.copyOfRange(list.toArray(), index, index + 20);
            state = getStateByOnline(fileList);
        }
        state.putInfo("start", index);
        state.putInfo("total", list.size());
        return state;
    }

    private State getStateByOnline(Object[] files) {
        MultiState state = new MultiState(true);
        BaseState fileState = null;
        File file = null;
        for (Object obj : files) {
            if (obj == null) {
                break;
            }
            file = (File) obj;
            fileState = new BaseState(true);
            fileState.putInfo("url", getPathByOnline(file));
            state.addState(fileState);
        }
        return state;
    }

    private String getPathByOnline(File file) {
        String path = file.getAbsolutePath();
        if (StringUtils.isNotBlank(path)) {
            path = file.getAbsolutePath().substring(file.getAbsolutePath().indexOf("resource")-1, file.getAbsolutePath().length()).replace("\\", "/");
            return path;
        } else {
            return path;
        }
    }

    public State listFile(HttpServletRequest request, int index) {
        String uploadPath = attachmentConfig.getPath() + Constants.STATIC_RESOURCE_BASE_PATH;
        File dir = new File(uploadPath);
        State state = null;
        if (!dir.exists()) {
            return new BaseState(false, AppInfo.NOT_EXIST);
        }
        if (!dir.isDirectory()) {
            return new BaseState(false, AppInfo.NOT_DIRECTORY);
        }
        Collection<File> list = FileUtils.listFiles(dir, null, true);
        if (index < 0 || index > list.size()) {
            state = new MultiState(true);
        } else {
            Object[] fileList = Arrays.copyOfRange(list.toArray(), index, index + 20);
            state = getState(fileList);
        }
        state.putInfo("start", index);
        state.putInfo("total", list.size());
        return state;
    }

    private State getState(Object[] files) {
        MultiState state = new MultiState(true);
        BaseState fileState = null;
        File file = null;
        for (Object obj : files) {
            if (obj == null) {
                break;
            }
            file = (File) obj;
            fileState = new BaseState(true);
            fileState.putInfo("url", getPath(file));
            System.out.println(getPath(file));
            state.addState(fileState);
        }
        return state;
    }

    private String getPath(File file) {
        String path = file.getAbsolutePath();

        if (StringUtils.isNotBlank(path)) {
            path = file.getAbsolutePath().substring(3, file.getAbsolutePath().length()).replace("\\", "/");
            return path;
        } else {
            return path;
        }
    }
}